//
//  DragButton.swift
//  elarc01
//
//  Created by elarc on 2016/12/6.
//  Copyright © 2016年 elarc. All rights reserved.
//

import UIKit

class DragButton: UIButton {
    
    var maxDistance:CGFloat?
    
    lazy var samllCircleView:UIView = {
        let samllCircleView = UIView()
        samllCircleView.backgroundColor = self.backgroundColor
        self.superview?.insertSubview(samllCircleView, belowSubview: self)
        return samllCircleView
    }()
    
    var images:[UIImage] = {
               var images:[UIImage] = []
                for i in 1...10 {
                    let image = UIImage(named:"0\(i)")
                    images.append(image!)
            }
             return images
    }()
    
    private var shapeLayer:CAShapeLayer = {
        
        let shapeLayer = CAShapeLayer()
//        shapeLayer.fillColor = self.backgroundColor!.CGColor
//        self.superview?.layer.insertSublayer(shapeLayer, below: self.layer)
        return shapeLayer
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUp()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    func setUp() {

        shapeLayer.fillColor = UIColor.redColor().CGColor
        
        self.superview?.layer.insertSublayer(shapeLayer, below: self.layer)

        let cornerRadius = (self.bounds.size.height > self.bounds.size.width ? self.bounds.size.width / 2.0 : self.bounds.size.height / 2.0) == 0.0 ? 20.0:40.0 as CGFloat
        self.setTitle("100", forState: .Normal)
        self.setTitleColor(UIColor.redColor(), forState: .Normal)
        maxDistance = cornerRadius * 4;
        
        self.layer.masksToBounds = true
        self.layer.cornerRadius = cornerRadius
        
        let samllCireleRect = CGRectMake(0, 0, cornerRadius * (2 - 0.5) , cornerRadius * (2 - 0.5))
        samllCircleView = UIView()
        self.samllCircleView.bounds = samllCireleRect
        samllCircleView.center = self.center
        samllCircleView.layer.cornerRadius = samllCircleView.bounds.size.width / 2;
        
        
        let pan = UIPanGestureRecognizer(target: self,action: #selector(DragButton.pan(_:)))
        self.addGestureRecognizer(pan)
        
        self.addTarget(self, action: #selector(DragButton.btnClick), forControlEvents: UIControlEvents.TouchUpInside)

    }

    func startDestroyAnimations() {
        
        let ainmImageView = UIImageView(frame:self.frame)
        ainmImageView.animationImages = self.images
        ainmImageView.animationRepeatCount = 1
        ainmImageView.animationDuration = 0.5
        ainmImageView.startAnimating()
        
        self.superview?.addSubview(ainmImageView)
    }
    
    func btnClick() {
        startDestroyAnimations()
        killAll()
    }
    
    func pointToPoitnDistanceWithPoint(pointA:CGPoint,pointB:CGPoint) -> CGFloat {
        let offestX = pointA.x - pointB.x
        let offestY = pointA.y - pointB.y
        let dist = CGFloat(sqrtf(Float(offestX * offestX + offestY * offestY)))
        return dist
    }

    func pathWithBigCirCleView(bigCirCleView:UIView,smallCirCleView:UIView) -> UIBezierPath {
        
        let bigCenter = bigCirCleView.center;
        let x2 = bigCenter.x;
        let y2 = bigCenter.y;
        let r2 = bigCirCleView.bounds.size.width / 2;
        
        let smallCenter = smallCirCleView.center;
        let x1 = smallCenter.x;
        let y1 = smallCenter.y;
        let r1 = smallCirCleView.bounds.size.width / 2;
        
        // 获取圆心距离
        let d = self.pointToPoitnDistanceWithPoint((self.samllCircleView.center), pointB: self.center)
        
        let sinθ = (x2 - x1) / d;
        let cosθ = (y2 - y1) / d;
        
        // 坐标系基于父控件
        let pointA = CGPointMake(x1 - r1 * cosθ , y1 + r1 * sinθ);
        let pointB = CGPointMake(x1 + r1 * cosθ , y1 - r1 * sinθ);
        let pointC = CGPointMake(x2 + r2 * cosθ , y2 - r2 * sinθ);
        let pointD = CGPointMake(x2 - r2 * cosθ , y2 + r2 * sinθ);
        let pointO = CGPointMake(pointA.x + d / 2 * sinθ , pointA.y + d / 2 * cosθ);
        let pointP = CGPointMake(pointB.x + d / 2 * sinθ , pointB.y + d / 2 * cosθ);
        
        let path = UIBezierPath()
        // A
        path.moveToPoint(pointA)
        // AB
        path.addLineToPoint(pointB)
        // 绘制BC曲线
        path.addQuadCurveToPoint(pointC, controlPoint: pointP)
        // CD
        path.addLineToPoint(pointD)
        // 绘制DA曲线
        path.addQuadCurveToPoint(pointA, controlPoint: pointO)
        return path
    }
    
    func pan(pan:UIPanGestureRecognizer) {
        
        self.layer.removeAnimationForKey("shake")
        
        let panPoint = pan.translationInView(self)
        var changeCenter = self.center

        changeCenter.x += panPoint.x
        changeCenter.y += panPoint.y
        self.center = changeCenter
        
        pan.setTranslation(CGPointZero, inView: self)
    
        
        let dist = self.pointToPoitnDistanceWithPoint(self.center, pointB: self.samllCircleView.center)

        if dist < maxDistance {
            
            let cornerRadius = (self.bounds.size.height > self.bounds.size.width ? self.bounds.size.width / 2 : self.bounds.size.height / 2)
            let samllCrecleRadius = cornerRadius - dist / 10
            samllCircleView.bounds = CGRectMake(0, 0, samllCrecleRadius * (2 - 0.5), samllCrecleRadius * (2 - 0.5))
            samllCircleView.layer.cornerRadius = samllCircleView.bounds.size.width / 2
            
            if samllCircleView.hidden == false && dist > 0 {
                self.shapeLayer.path = self.pathWithBigCirCleView(self, smallCirCleView: samllCircleView).CGPath
            }
        } else {
            self.shapeLayer.removeFromSuperlayer()
    
            
            self.samllCircleView.hidden = true
        }
        
        if pan.state == UIGestureRecognizerState.Ended {
            
            if dist > maxDistance {
                startDestroyAnimations()
                killAll()
                
            } else {
                self.shapeLayer.removeFromSuperlayer()
                
                UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 1, options: UIViewAnimationOptions.CurveEaseInOut, animations: { 
                    self.center = self.samllCircleView.center
                    }, completion: { (finished) in
                    self.samllCircleView.hidden = false
                })
            }
        }

    }
    
    func killAll() {
        self.removeFromSuperview()
        self.samllCircleView.removeFromSuperview()
        self.shapeLayer.removeFromSuperlayer()
    }
    
    
    
    
}